//
//  JNCardSDKNewFivMakeRepayVC.m
//  TwoOneEight
//
//  Created by jinniu2 on 2019/4/23.
//  Copyright © 2019年 Jinniu. All rights reserved.
//

#import "JNCardSDKNewFivMakeRepayVC.h"
#import "JNCardSDKPlanModelView.h"
#import "JNCardSDKFivMakePlanReqModel.h"
#import "JNCardSDKFivPreViewModel.h"
#import "JNCardSDKPreViewPlanVC.h"
#import "JNCardSDKCommonWebView.h"
#import "SWAlertController.h"
#import "JNCardSDKMyWebView.h"
#import "JNCardSDKFivNetFile.h"
#import "JNCardSDKCardDetailVC.h"
#import "JNCardSDKDLMyCouponModel.h"
#import "DLPickerView.h"
#import "JNCardSDKNewConsumptionPatternsCtr.h"
#import "JNCardSDKNewConsumTypeModel.h"
#import "JNCardSDKFVRepayPlanDetailVC.h"
@interface JNCardSDKNewFivMakeRepayVC ()<UITextFieldDelegate,UIScrollViewDelegate>{
    UIScrollView * _bgScro;
    UITextField * _payTF,*_moneyTF;
    NSString * _planPayMoney, *_planFirstMoney;
    UIView * _bgView,*_btnBarView, *_jihuaModelView,*_bottomBGView;
    JNCardSDKPlanModelView * _modelView;
    UIButton * _selectBtn, * _generateBtn,*_moneyBtn,*_selModelBtn;
    NSMutableDictionary * _paraDic;
    NSInteger _createOtherUICount, _couponUseAbleCount;
    UILabel * _noticeLab,* _dongTaiLab,* _dongTaiLab1;
    NSMutableArray *_buttomBtnArr,*_couponUseableArr;
    UILabel *_modelLab/*模式label*/,*_chosedCouponLab,*_leftModelLab,*_bottomRightLab,*_bottomThirdLab;
    BOOL _isOpenSmall,_isOpenBig;//是否开启多消模式（isOpenSmall:小额多消，isOpenBig：大额多消）
    JNCardSDKDLMyCouponModel *_couponModel;
}
@property (nonatomic,strong) JNCardSDKFivPreViewModel *mainModel;
@property (nonatomic,strong) NSDictionary *mainDic;
@property(nonatomic,strong)dispatch_group_t gropuThread;
@property(nonatomic,retain)JNCardSDKNewConsumTypeModel * userTypeModel;
@end

@implementation JNCardSDKNewFivMakeRepayVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.isHideNavBar = YES;
    self.isHideBottomLine = YES;
    _buttomBtnArr = [NSMutableArray new];
    _couponUseableArr = [NSMutableArray new];
    self.view.backgroundColor = [UIColor colorWithRed:244.0/255.0 green:244.0/255.0 blue:244.0/255.0 alpha:1.0];
    NSNotificationCenter * center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(noVerifyGotoCreatePlan) name:@"createPlanDirectly" object:nil];
    _paraDic = [NSMutableDictionary new];
    [_paraDic setObject:@"1" forKey:@"OpenUnion"];//默认开通银联
    [_paraDic setObject:self.cardInfoModel.userCreditCardId forKey:@"UserCreditCardId"];
    [_paraDic setObject:@"3" forKey:@"BackType"];//2019-11-6消费模式写死默认传3
    [self isTodayCanMakePlan];
    [self getUserConsumeType];
}
-(UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}
-(void)noVerifyGotoCreatePlan{
    [self getChannelType];
}
-(void)getUserConsumeType{
    NSString * url = [JNCardSDKWorkUrl returnURL:Interface_For_GetConsumeSetInfo];
    NSMutableDictionary * p = [JNCardSDKReuserFile returnHYKBaseDic];
    [SVProgressHUD show];
    [PGNetworkHelper GET:url parameters:p cache:NO responseCache:nil success:^(id responseObject) {
        [SVProgressHUD dismiss];
        if ([responseObject[@"status"] integerValue]==1) {
            self.userTypeModel = [JNCardSDKNewConsumTypeModel mj_objectWithKeyValues:responseObject[@"data"]];
            [self createUI];
        }else{
            [JNCardSDKMytools warnText:responseObject[@"msg"] status:JNCardSDKError];
        }
    } failure:^(NSError *error) {
        [SVProgressHUD dismiss];
    }];
}
-(void)isTodayCanMakePlan{
    //当前时间对比13：30，看当天执行按钮是否可用
    NSDate * currentDate = [NSDate date];
    NSString * currentDayStr = [JNCardSDKMytools dateToDateStr:currentDate];
    currentDayStr = [currentDayStr stringByReplacingCharactersInRange:NSMakeRange(11, 8) withString:@"13:30:00"];
    NSDate * standDate = [JNCardSDKMytools dateStrToDate:currentDayStr];
    NSDate * nowDate = [currentDate dateByAddingHours:8];
    if ([JNCardSDKMytools compareOneDay:nowDate withAnotherDay:standDate]==1) {
        //当前时间超过13：30
        [_paraDic setObject:@"0" forKey:@"Today"];
    }else{
        //后来又加上了判断当天是否是节假日，如果是即便是没超过13：30也不可选
        if ([JNCardSDKCalculaterBillPayDay holidayListCanChose:nowDate isFromSelect:NO]==YES) {
            [_paraDic setObject:@"1" forKey:@"Today"];
        }else{
            [_paraDic setObject:@"0" forKey:@"Today"];
        }
    }
}
#pragma mark 点击事件
-(void)generateBtnClick:(UIButton*)sender{
    if (_payTF.text.length==0) {
        [JNCardSDKMytools warnText:@"计划还款金额不能为空" status:JNCardSDKError];
        return;
    }
    if (_moneyTF.text.length==0) {
        [JNCardSDKMytools warnText:@"计划定金金额不能为空" status:JNCardSDKError];
        return;
    }
    NSInteger tmpMoney = [JNCardSDKReuserFile calculateMinPayMoneyWithTotalMoney:_payTF.text];
    if ([_moneyTF.text integerValue]<tmpMoney) {
        [JNCardSDKMytools warnText:[NSString stringWithFormat:@"计划定金不能小于%ld",tmpMoney] status:JNCardSDKError];
        return;
    }
    if(!self.gropuThread)self.gropuThread = dispatch_group_create();
    [SVProgressHUD show];
    [self getChannelType];
    dispatch_group_notify(self.gropuThread, dispatch_get_main_queue(), ^{
        [SVProgressHUD dismiss];
    });
}
-(void)previewPlanDetailClick{
    JNCardSDKFivPreViewModel * model = self.mainModel;
    JNCardSDKPreViewPlanVC * vc = [JNCardSDKPreViewPlanVC new];
    vc.isFromFivPre = YES;
    vc.myTitle = @"计划预览";
    vc.planID = model.planid;
    vc.backDic = model.mj_keyValues;
    vc.bankCardID = self.cardInfoModel.userCreditCardId;
    vc.handMoney =  [NSString stringWithFormat:@"%@",[JNCardSDKMytools returnDecimalNumStr:[NSString stringWithFormat:@"%f",model.money]]];
    vc.saleMoney = [NSString stringWithFormat:@"%@",[JNCardSDKMytools returnDecimalNumStr:[NSString stringWithFormat:@"%f",model.salemoney]]];
    vc.bankNum = self.cardInfoModel.bankNum;
    vc.planMoney = model.vicPlanPay;
    vc.planDingjin = model.vicPlanMoney;
    [self.navigationController pushViewController:vc animated:YES];
}
-(void)startPlanClick{
    [self verifyPayPasswordWithTitle:@"你将启动计划，请输入支付密码验证"];
}
-(void)getChannelType{
    dispatch_group_enter(self.gropuThread);
    NSMutableDictionary * p = [JNCardSDKReuserFile returnHYKBaseDic];
    [p addEntriesFromDictionary:_paraDic];
    [p setObject:@"3" forKey:@"CalcType"];
    NSString * url = [JNCardSDKWorkUrl returnURL:Interface_For_REPAYPLANTRYCREATE];
    [PGNetworkHelper POST:url parameters:p cache:NO responseCache:nil success:^(id responseObject) {
        if ([responseObject[@"status"] integerValue]==1) {
            self.mainModel = [JNCardSDKFivPreViewModel mj_objectWithKeyValues:responseObject];
            self.mainModel.vicPlanPay = self->_payTF.text;
            self.mainModel.vicPlanMoney = self->_moneyTF.text;
            self->_modelView = [[JNCardSDKPlanModelView alloc]initWithFrame:Frame(0, CGRectGetMaxY(self->_generateBtn.frame)+70, IPHONE_WIDTH, 206)];
            self->_modelView.model = self.mainModel;
            //            修改scrollView的底部对齐使得空出启动计划按钮的位置
            self->_bgScro.sd_layout.spaceToSuperView(UIEdgeInsetsMake(kTopHeight+65, 0, 80, 0));
            [self->_bgScro addSubview:self->_modelView];
            [self createBottomBtnView];
            self->_generateBtn.userInteractionEnabled = NO;
            [self->_generateBtn setTitleColor:[UIColor colorWithHue:0 saturation:0 brightness:0.72 alpha:1] forState:UIControlStateNormal];
            self->_generateBtn.backgroundColor = [UIColor colorWithHue:1 saturation:0 brightness:0.93 alpha:1];
        }else if([responseObject[@"status"] integerValue]==2){
            NSInteger open = [responseObject[@"data"][@"open"] integerValue];
            NSString * url  =responseObject[@"data"][@"url"];
            if (open ==1 && url.length>0) {
                [SVProgressHUD dismiss];
                [self gotoWebViewVerify:url isSmsVerify:NO];
            }
        }else{
            [SVProgressHUD dismiss];
            NSString *msgStr = [NSString stringWithFormat:@"%@",responseObject[@"msg"]];
            [JNCardSDKMytools warnText:msgStr status:JNCardSDKError];
        }
        dispatch_group_leave(self.gropuThread);
    } failure:^(NSError *error) {
        dispatch_group_leave(self.gropuThread);
    }];
}

-(void)gotoWebViewVerify:(NSString*)webUrl isSmsVerify:(BOOL)isVerify{//前往网页认证
//    JNCardSDKCommonWebView * w = [JNCardSDKCommonWebView new];
//    if([JNCardSDKMytools IsChinese:webUrl]){
//        webUrl = [webUrl stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
//    }
//    w.successBlock = ^{
//        [self verifyPayPasswordWithTitle:@"你将启动计划，请输入支付密码验证"];
//    };
//    w.isGoToSMSVerify = isVerify;
//    w.url = webUrl;
//    w.cardModel = self.cardInfoModel;
//    [self.navigationController pushViewController:w animated:YES];

    JNCardSDKMyWebView * w = [JNCardSDKMyWebView new];
    if([JNCardSDKMytools IsChinese:webUrl]){
        webUrl = [webUrl stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    }
    w.successBlock = ^{
        [self verifyPayPasswordWithTitle:@"你将启动计划，请输入支付密码验证"];
    };
    w.isGoToSMSVerify = isVerify;
    w.currentWebUrl = webUrl;
    w.isFromFivMakePlan = YES;
    w.cardModel = self.cardInfoModel;
    [self.navigationController pushViewController:w animated:YES];
}
//-(void)gotoSMSVerify{//前往短信认证
//    LianDongVerifyVC * vc = [LianDongVerifyVC new];
//    vc.successBlock = ^{
//        [self verifyPayPasswordWithTitle:@"你将启动计划，请输入支付密码验证"];
//    };
//    vc.cardID = self.cardInfoModel.UserCreditCardId;
//    [self.navigationController pushViewController:vc animated:YES];
//}
-(void)verifyPayPasswordWithTitle:(NSString*)title{
    [self showAlertWithTitle:@"温馨提示" message:@"你将启动并执行该计划，请确保卡内有足够本金用于执行，以免造成计划暂停而影响还款" appearanceProcess:^(SWAlertController * _Nullable alertMaker) {
        alertMaker.addActionCancelTitle(@"取消",[UIColor lightGrayColor]);
        alertMaker.addActionDefaultTitle(@"确定",[UIColor redColor]);
    } actionsBlock:^(NSInteger buttonIndex, UIAlertAction * _Nullable action, SWAlertController * _Nullable alertSelf) {
        if (buttonIndex==1) {
            [self savePlanToSQL];
        }
        
    }];
}

#pragma mark 请求
-(void)savePlanToSQL{
    [JNCardSDKFivNetFile savePlanIntoSQLWithKey:self.mainModel.data.theKey couponID:_couponModel.UserCouponId andBackBlock:^(NSDictionary *backDic) {//返回到这一定成功
        [JNCardSDKFivNetFile makePlanToExcutingWithPlanID:self.mainModel.planid andBackBlock:^(NSDictionary *backDic) {
            for (UIViewController *controller in self.navigationController.viewControllers) {
                if ([controller isKindOfClass:[JNCardSDKCardDetailVC class]]) {
                    [self.navigationController popToViewController:controller animated:YES];
                    break;
                }
            }
        }];
    }];
}

#pragma mark textField监听和代理
- (void)textFieldDidChangeValue:(UITextField*)textField{
    JNCardSDKVicSingleObject * single = [JNCardSDKVicSingleObject getInstance];
    if (textField.tag == 10) {//计划还款
        NSInteger tmpMoney = [JNCardSDKReuserFile calculateMinPayMoneyWithTotalMoney:textField.text];
        if (tmpMoney>single.MaxPayAmount) {
            _noticeLab.text = [NSString stringWithFormat:@"计划定金不能大于%.2f，请重新输入！",single.MaxPayAmount];
            textField.text = @"";
        }else{
            _noticeLab.text = [NSString stringWithFormat:@"计划定金不能小于%ld",tmpMoney];
        }
        [self safeTextField:textField];//避免非法输入
        [_paraDic setObject:textField.text forKey:@"TotalMoney"];
    }else{//计划定金
        if (_payTF.text.length==0) {
            textField.text = @"";
            [JNCardSDKMytools warnText:@"计划还款不能为空" status:JNCardSDKError];
        }else{
            _noticeLab.text = [JNCardSDKCalculaterBillPayDay returnNoticeMsgWithPlanMoney:textField.text andPayMoney:_payTF.text];
            [self safeTextField:textField];
            [_paraDic setObject:textField.text forKey:@"BuysCount"];
        }
    }
    if (_payTF.text.length==0&&_moneyTF.text.length==0) {
        _noticeLab.text = @"计划定金不得低于计划还款总额的5%" ;
    }
}

-(void)textFieldDidBeginEditing:(UITextField *)textField{
    _generateBtn.backgroundColor = [UIColor colorWithHue:1 saturation:0.72 brightness:0.9 alpha:1];
    [self->_generateBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    _generateBtn.userInteractionEnabled = YES;
    [_bottomBGView removeFromSuperview];
    [_modelView removeFromSuperview];
    [_bgView setupAutoHeightWithBottomView:_generateBtn bottomMargin:10];
    [_bgScro setupAutoContentSizeWithBottomView:_bgView bottomMargin:30];
    _moneyTF.text = @"";
}
-(void)textFieldDidEndEditing:(UITextField *)textField{
    if (textField.tag == 10) {//计划还款
        if ([textField.text integerValue]<1000) {
            if (textField.text.length>0) {
                textField.text = @"";
                [JNCardSDKMytools warnText:@"计划还款不能低于1000元" status:JNCardSDKError];
            }
        }else{
            _planPayMoney = textField.text;
        }
    }else{//计划定金
        if ([textField.text integerValue]*20<[_planPayMoney integerValue]) {
            textField.text = @"";
            [JNCardSDKMytools warnText:@"计划定金不得低于计划还款总额的5%" status:JNCardSDKError];
        }else{
            _planFirstMoney = textField.text;
        }
    }
}
-(void)safeTextField:(UITextField*)textField{
    if ([textField.text containsString:@"."]) {
        textField.text = @"";
        [JNCardSDKMytools warnText:@"请勿输入小数" status:JNCardSDKError];
        return;
    }else if ([JNCardSDKMytools IsChinese:textField.text]==YES){
        textField.text = @"";
        [JNCardSDKMytools warnText:@"请勿输入中文" status:JNCardSDKError];
        return;
    }
}
#pragma mark 视图创建
-(void)createUI{
    [self createHeadInfoView];//创建头部
    _bgScro = [UIScrollView new];
    _bgScro.showsVerticalScrollIndicator = NO;
    _bgScro.delegate = self;
    _bgScro.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_bgScro];
    _bgScro.sd_layout.spaceToSuperView(UIEdgeInsetsMake(kTopHeight+65, 0, 0, 0));
    [self createDefaultView];
}
-(void)createBottomBtnView{
    _bottomBGView = [UIView new];
    _bottomBGView.backgroundColor = [UIColor whiteColor];
    [_bgScro addSubview:_bottomBGView];
    _bottomBGView.sd_layout.topSpaceToView(_modelView, 20).leftEqualToView(_bgScro).rightEqualToView(_bgScro).heightIs(45);
    UIButton * leftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [leftBtn setTitle:@"预览计划明细" forState:UIControlStateNormal];
    leftBtn.backgroundColor = [UIColor colorWithHue:0.83 saturation:0.01 brightness:0.7 alpha:1];
    [leftBtn addTarget:self action:@selector(previewPlanDetailClick) forControlEvents:UIControlEventTouchUpInside];
    leftBtn.cornerRadius = 3;
    [_bottomBGView addSubview:leftBtn];
    leftBtn.sd_layout.leftSpaceToView(_bottomBGView, 10).topSpaceToView(_bottomBGView, 10).widthIs((IPHONE_WIDTH-30)/2.f).heightIs(45);
    UIButton * rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [rightBtn setTitle:@"启动计划" forState:UIControlStateNormal];
    rightBtn.backgroundColor = [UIColor colorWithHue:1 saturation:0.72 brightness:0.9 alpha:1];
    rightBtn.cornerRadius = 3;
    [rightBtn addTarget:self action:@selector(startPlanClick) forControlEvents:UIControlEventTouchUpInside];
    [_bottomBGView addSubview:rightBtn];
    rightBtn.sd_layout.leftSpaceToView(leftBtn, 10).centerYEqualToView(leftBtn).rightSpaceToView(_bottomBGView, 10).heightIs(45);
    [_bgScro setupAutoContentSizeWithBottomView:_bottomBGView bottomMargin:30];
    [self->_bgScro setNeedsLayout];
    [self->_bgScro layoutIfNeeded];
    [self->_bgScro setContentOffset:CGPointMake(0, _bgScro.contentSize.height-(IPHONE_HEIGHT-(kTopHeight+65))) animated:YES];
}
-(void)createDefaultView{
    UILabel * titleLab = [UILabel labelWithTitle:@"计划金额" color:[UIColor blackColor] fontSize:16];
    [_bgScro addSubview:titleLab];
    titleLab.sd_layout.leftSpaceToView(_bgScro, 10).topSpaceToView(_bgScro, 10).heightIs(19);
    [titleLab setSingleLineAutoResizeWithMaxWidth:200];
    UILabel * descLab = [UILabel labelWithTitle:@"配置计划还款额度及可用本金" color:[UIColor lightGrayColor] fontSize:13];
    [_bgScro addSubview:descLab];
    descLab.sd_layout.leftSpaceToView(_bgScro, 10).topSpaceToView(titleLab, 10).heightIs(12);
    [descLab setSingleLineAutoResizeWithMaxWidth:300];
    _bgView = [UIView new];
    _bgView.backgroundColor = [UIColor whiteColor];
    [_bgScro addSubview:_bgView];
    _bgView.sd_layout.leftSpaceToView(_bgScro, 0).rightSpaceToView(_bgScro, 0).topSpaceToView(descLab, 10);
    
    UIView *topGrayView = [UIView new];
    topGrayView.layer.masksToBounds = YES;
    topGrayView.layer.cornerRadius = 6;
    topGrayView.layer.borderWidth = 0.8;
    topGrayView.layer.borderColor = [UIColor colorWithHue:0 saturation:0 brightness:0.95 alpha:1].CGColor;
    topGrayView.backgroundColor = [UIColor colorWithRed:0.98 green:0.98 blue:0.98 alpha:1];
    [_bgView addSubview:topGrayView];
    topGrayView.sd_layout.topSpaceToView(_bgView, 0).leftSpaceToView(_bgView, 10).rightSpaceToView(_bgView, 10);
    
    UILabel * tmpPlanPayLab = [UILabel labelWithTitle:@"计划还款" color:[UIColor blackColor] fontSize:16];
    [topGrayView addSubview:tmpPlanPayLab];
    tmpPlanPayLab.sd_layout.leftSpaceToView(topGrayView, 15).topSpaceToView(topGrayView, 20).heightIs(14);
    [tmpPlanPayLab setSingleLineAutoResizeWithMaxWidth:200];
    UIView *centerLineView = [UIView new];
    centerLineView.backgroundColor = [UIColor colorWithRed:0.95 green:0.95 blue:0.95 alpha:1];
    [topGrayView addSubview:centerLineView];
    centerLineView.sd_layout.topEqualToView(topGrayView).bottomEqualToView(topGrayView).centerXEqualToView(topGrayView).widthIs(0.6);
    
    UILabel * tmpFeeLab = [UILabel labelWithTitle:@"计划定金" color:[UIColor blackColor] fontSize:16];
    [topGrayView addSubview:tmpFeeLab];
    tmpFeeLab.sd_layout.leftSpaceToView(centerLineView, 15).centerYEqualToView(tmpPlanPayLab).heightIs(14);
    [tmpFeeLab setSingleLineAutoResizeWithMaxWidth:200];
    UILabel *mLab = [UILabel labelWithTitle:@"¥" color:[UIColor blackColor] font:[UIFont boldSystemFontOfSize:16] alignment:NSTextAlignmentLeft];
    [topGrayView addSubview:mLab];
    mLab.sd_layout.topSpaceToView(tmpPlanPayLab, 18).leftSpaceToView(topGrayView, 15).heightIs(20).widthIs(12);
    _payTF = [UITextField new];
    _payTF.tag = 10;
    _payTF.delegate = self;
    _payTF.keyboardType = UIKeyboardTypeNumberPad;
    _payTF.textAlignment = NSTextAlignmentLeft;
    [_payTF addTarget:self
               action:@selector(textFieldDidChangeValue:)
     forControlEvents:UIControlEventEditingChanged];
    _payTF.placeholder = @"输入还款金额";
    _payTF.font = [UIFont systemFontOfSize:14];
    [topGrayView addSubview:_payTF];
    _payTF.sd_layout.leftSpaceToView(mLab,2).centerYEqualToView(mLab).heightIs(30).rightSpaceToView(centerLineView, 0);
    UILabel *mLab1 = [UILabel labelWithTitle:@"¥" color:[UIColor blackColor] font:[UIFont boldSystemFontOfSize:16] alignment:NSTextAlignmentLeft];
    [topGrayView addSubview:mLab1];
    mLab1.sd_layout.centerYEqualToView(mLab).leftSpaceToView(centerLineView, 15).heightIs(20).widthIs(12);
    _moneyTF = [UITextField new];
    _moneyTF.tag = 11;
    _moneyTF.delegate = self;
    [_moneyTF addTarget:self action:@selector(textFieldDidChangeValue:)
       forControlEvents:UIControlEventEditingChanged];
    _moneyTF.keyboardType = UIKeyboardTypeNumberPad;
    _moneyTF.textAlignment = NSTextAlignmentLeft;
    NSString *modelMoneyStr = [NSString stringWithFormat:@"%@",[self.mainDic objectForKey:@"capitalSelectMode"]];
    _moneyTF.placeholder = [modelMoneyStr isEqualToString:@"1"]?@"选择计划可用本金":@"输入计划可用本金";
    _moneyTF.font = [UIFont systemFontOfSize:14];
    [topGrayView addSubview:_moneyTF];
    _moneyTF.sd_layout.leftSpaceToView(mLab1,2).centerYEqualToView(_payTF).heightIs(30).rightSpaceToView(topGrayView, 0);
    
    _moneyBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _moneyBtn.hidden = [modelMoneyStr isEqualToString:@"1"]?NO:YES;
    [_moneyBtn addTarget:self action:@selector(moneyBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [topGrayView addSubview:_moneyBtn];
    _moneyBtn.sd_layout.leftSpaceToView(mLab1, 2).centerYEqualToView(_payTF).heightIs(30).rightSpaceToView(topGrayView, 0);
    UIView * hLine = [UIView new];
    hLine.backgroundColor = [UIColor colorWithHue:0.99 saturation:0.07 brightness:0.96 alpha:1];
    [topGrayView addSubview:hLine];
    hLine.sd_layout.leftEqualToView(topGrayView).rightEqualToView(topGrayView).topSpaceToView(mLab, 18).heightIs(0.6);
    UIView *fView = [UIView new];
    fView.backgroundColor = [UIColor colorWithHue:1 saturation:0.04 brightness:0.98 alpha:1];
    [topGrayView addSubview:fView];
    fView.sd_layout.topSpaceToView(hLine, 0).leftEqualToView(topGrayView).rightEqualToView(topGrayView).heightIs(32);
    _noticeLab = [UILabel labelWithTitle:@"计划定金不得低于计划还款总额的5%" color:[UIColor redColor] fontSize:12];
    [fView addSubview:_noticeLab];
    _noticeLab.sd_layout.centerYEqualToView(fView).leftSpaceToView(fView, 15).heightIs(12);
    [_noticeLab setSingleLineAutoResizeWithMaxWidth:IPHONE_WIDTH-50];
    [topGrayView setupAutoHeightWithBottomView:fView bottomMargin:0];

    UILabel *leftLab = [UILabel labelWithTitle:@"消费模式" color:[UIColor blackColor] fontSize:14 alignment:NSTextAlignmentLeft];
    [_bgView addSubview:leftLab];
    leftLab.sd_layout.topSpaceToView(topGrayView, 29).leftSpaceToView(_bgView, 13).heightIs(16);
    
    [leftLab setSingleLineAutoResizeWithMaxWidth:100];
    UILabel *rightLab = [UILabel labelWithTitle:@"合理的配置消费模式，助于完美账单促信用" color:[UIColor colorWithRed:0.55 green:0.55 blue:0.55 alpha:1] fontSize:12 alignment:NSTextAlignmentLeft];
    [_bgView addSubview:rightLab];
    rightLab.sd_layout.topSpaceToView(leftLab, 8).leftSpaceToView(_bgView, 13).rightEqualToView(_bgView).heightIs(12);
    
    UIImageView *rightImg = [UIImageView new];
    rightImg.image = Image(@"右箭头");
    [_bgView addSubview:rightImg];
    rightImg.sd_layout.centerYEqualToView(leftLab).rightSpaceToView(_bgView, 10).heightIs(16).widthEqualToHeight();
    
    _selModelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_selModelBtn setTitle:self.userTypeModel.name forState:UIControlStateNormal];
    [_selModelBtn setTitleColor:[UIColor colorWithRed:0.2 green:0.65 blue:0.86 alpha:1] forState:UIControlStateNormal];
    _selModelBtn.titleLabel.font = [UIFont systemFontOfSize:16];
    [_selModelBtn addTarget:self action:@selector(selModelBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [_bgView addSubview:_selModelBtn];
    _selModelBtn.sd_layout.centerYEqualToView(leftLab).rightSpaceToView(rightImg, 6);
    [_selModelBtn setupAutoSizeWithHorizontalPadding:0 buttonHeight:30];
    
    UIView *secondGrayView = [UIView new];
    secondGrayView.layer.masksToBounds = YES;
    secondGrayView.layer.cornerRadius = 6;
    secondGrayView.layer.borderWidth = 0.8;
    secondGrayView.layer.borderColor = [UIColor colorWithHue:0 saturation:0 brightness:0.95 alpha:1].CGColor;
    secondGrayView.backgroundColor = [UIColor colorWithHue:0 saturation:0 brightness:0.98 alpha:1];
    [_bgView addSubview:secondGrayView];
    secondGrayView.sd_layout.topSpaceToView(rightLab, 10).leftSpaceToView(_bgView, 13).rightSpaceToView(_bgView, 13);
    
    _dongTaiLab = [UILabel labelWithTitle:self.userTypeModel.remark color:[UIColor blackColor] fontSize:14 alignment:NSTextAlignmentLeft];
    [secondGrayView addSubview:_dongTaiLab];
    _dongTaiLab.sd_layout.topSpaceToView(secondGrayView, 20).leftSpaceToView(secondGrayView, 15).rightSpaceToView(secondGrayView, 15).heightIs(12);
    JNCardSDKVicSingleObject * single = [JNCardSDKVicSingleObject getInstance];
    NSString * msg = [NSString stringWithFormat:@"1.计划执行效率:单笔-%@%%+%@\n2.多商户落地小额通道，适用可执行时间长的计划\n3.支持一笔还款搭配多笔消费",[JNCardSDKMytools returnDecimalNumStr:[NSString stringWithFormat:@"%lf",single.HighRate]],[JNCardSDKMytools returnDecimalNumStr:[NSString stringWithFormat:@"%lf",single.ServerMoney]]];
    _dongTaiLab1 = [UILabel labelWithTitle:msg color:[UIColor colorWithRed:0.5 green:0.5 blue:0.5 alpha:1] fontSize:12 alignment:NSTextAlignmentLeft];
    [secondGrayView addSubview:_dongTaiLab1];
    _dongTaiLab1.sd_layout.topSpaceToView(_dongTaiLab, 15).leftSpaceToView(secondGrayView, 15).rightSpaceToView(secondGrayView, 15).autoHeightRatio(0);
    
    [secondGrayView setupAutoHeightWithBottomView:_dongTaiLab1 bottomMargin:20];

    _generateBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _generateBtn.backgroundColor = [UIColor colorWithRed:0.13 green:0.62 blue:0.85 alpha:1];
    _generateBtn.cornerRadius = 2;
    [_generateBtn addTarget:self action:@selector(generateBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [_generateBtn setTitle:@"预生成" forState:UIControlStateNormal];
    [_bgView addSubview:_generateBtn];
    _generateBtn.sd_layout.leftSpaceToView(_bgView, 10).rightSpaceToView(_bgView, 10).topSpaceToView(secondGrayView, 20).heightIs(50);
    [_bgView setupAutoHeightWithBottomView:_generateBtn bottomMargin:10];
    [_bgScro setupAutoContentSizeWithBottomView:_bgView bottomMargin:10];
}
-(void)selModelBtnClick:(UIButton*)sender{
    
    JNCardSDKNewConsumptionPatternsCtr *vc = [JNCardSDKNewConsumptionPatternsCtr new];
    [vc setReturnPageIndexBlock:^(JNCardSDKNewConsumTypeModel * _Nonnull selModel) {
        self.userTypeModel = selModel;
        [self->_selModelBtn setTitle:selModel.name forState:UIControlStateNormal];
        self->_dongTaiLab.text = selModel.remark;
    }];
    [self.navigationController pushViewController:vc animated:YES];
}

-(void)moneyBtnClick{
    [_payTF endEditing:YES];
    if (_payTF.text.length==0) {
        [JNCardSDKMytools warnText:@"计划还款不能为空" status:JNCardSDKError];
        return;
    }else{
        JNCardSDKVicSingleObject *single = [JNCardSDKVicSingleObject getInstance];
        NSInteger tmpMoney = [JNCardSDKReuserFile calculateMinPayMoneyWithTotalMoney:_payTF.text];
        NSArray *arr = [self.mainDic objectForKey:@"capitalList"];
        NSMutableArray *userArr = [NSMutableArray new];
        for (int i=0; i<arr.count; i++) {
            NSString *str = [NSString stringWithFormat:@"%@",[arr objectAtIndex:i]];
            if ([str integerValue]>=tmpMoney&&[str integerValue]<=single.MaxPayAmount) {
                [userArr addObject:str];
            }
        }
        if (userArr.count==0) {
            [JNCardSDKMytools warnText:@"没有可用的定金计划金额" status:JNCardSDKError];
            return;
        }
        DLPickerView * picker = [[DLPickerView alloc]initWithDataSource:userArr withSelectedItem:nil withSelectedBlock:^(id  _Nonnull item) {
            if (![self->_moneyTF.text isEqualToString:item]) {
                self->_moneyTF.text = item;
                [self->_paraDic setObject:self->_moneyTF.text forKey:@"BuysCount"];
                self->_generateBtn.backgroundColor = [UIColor colorWithHue:1 saturation:0.72 brightness:0.9 alpha:1];
                [self->_generateBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
                self->_generateBtn.userInteractionEnabled = YES;
                [self->_bottomBGView removeFromSuperview];
                [self->_modelView removeFromSuperview];
                [self->_bgView setupAutoHeightWithBottomView:self->_generateBtn bottomMargin:10];
                [self->_bgScro setupAutoContentSizeWithBottomView:self->_bgView bottomMargin:10];
            }
        }];
        [picker show];
    }
}

-(void)bottomBtnClick:(UIButton*)sender{
    
    for (UIButton *button in _buttomBtnArr) {
        button.selected = NO;
    }
    UIButton *selectedBtn = _buttomBtnArr[sender.tag-10086];
    selectedBtn.selected = YES;
    NSString *leftModelStr=@"";
    NSString *modelStr=@"";
    [_paraDic setObject:@"3" forKey:@"BackType"];
    if (sender.tag-10086==0) {
//        [_paraDic setObject:self->_isOpenSmall?@"3":@"1" forKey:@"BackType"];//消费模式
        self->_bottomThirdLab.text = self->_isOpenSmall?@"已开启多消模式":@"已开启单消模式";
        [_paraDic setObject:@"3" forKey:@"CaleType"];
        [_paraDic setObject:@"0" forKey:@"ChType"];
        NSString *noutfStr = [[NSString stringWithFormat:@"%@",self.mainDic[@"smallRemark"]] stringByRemovingPercentEncoding];
        leftModelStr = [NSString stringWithFormat:@"小额模式(%@)",noutfStr];
        modelStr = @"1.适用于可执行时间比较长的还款计划\n2.支持一笔还款搭配多笔消费，多商户落地小额通道";
        _leftModelLab.text = leftModelStr;
        _modelLab.text = modelStr;
        _bottomRightLab.text = @"商户落地小额通道";
        _modelLab.sd_layout.heightIs(ceilf([modelStr sizeWithFont:[UIFont systemFontOfSize:12] maxSize:CGSizeMake(IPHONE_WIDTH-50, 0)].height));
    }else{
//        [_paraDic setObject:self->_isOpenBig?@"3":@"1" forKey:@"BackType"];//消费模式
        self->_bottomThirdLab.text = self->_isOpenBig?@"已开启多消模式":@"已开启单消模式";
        [_paraDic setObject:@"4" forKey:@"CaleType"];
        [_paraDic setObject:@"1" forKey:@"ChType"];
        NSString *noutfStr = [[NSString stringWithFormat:@"%@",self.mainDic[@"bigRemark"]] stringByRemovingPercentEncoding];
        leftModelStr = [NSString stringWithFormat:@"大额模式(%@)",noutfStr];
        modelStr = @"1.适用于可执行时间比较紧凑的还款计划\n2.  系统自动匹配消费以及还款笔数，标准大额落地通道";
        _bottomRightLab.text = @"标准大额落地通道";
        _leftModelLab.text = leftModelStr;
        _modelLab.text = modelStr;
        _modelLab.sd_layout.heightIs(ceilf([modelStr sizeWithFont:[UIFont systemFontOfSize:12] maxSize:CGSizeMake(IPHONE_WIDTH-50, 0)].height));
    }
    _generateBtn.backgroundColor = [UIColor colorWithHue:1 saturation:0.72 brightness:0.9 alpha:1];
    [self->_generateBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    _generateBtn.userInteractionEnabled = YES;
    [_bottomBGView removeFromSuperview];
    [_modelView removeFromSuperview];
    [_bgView setupAutoHeightWithBottomView:_generateBtn bottomMargin:10];
    [_bgScro setupAutoContentSizeWithBottomView:_bgView bottomMargin:30];
}
-(void)backClick{
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)createHeadInfoView{
    UIView *topView = [UIView new];
    topView.backgroundColor = self.receiveColor;
    [self.view addSubview:topView];
    topView.sd_layout.topEqualToView(self.view).leftEqualToView(self.view).rightEqualToView(self.view).heightIs(kTopHeight);

    UIButton *button = [[UIButton alloc]initWithFrame:Frame(0, kStatusBarHeight, kNavBarHeight, kNavBarHeight)];
    [button setImage:Image(@"白色左箭头") forState:UIControlStateNormal];
    [button addTarget:self action:@selector(backClick) forControlEvents:UIControlEventTouchUpInside];
    [topView addSubview:button];

    UILabel *lab = [UILabel labelWithTitle:@"设置还款计划" color:[UIColor whiteColor] fontSize:18 alignment:NSTextAlignmentCenter];
    [topView addSubview:lab];
    lab.sd_layout.centerYEqualToView(button).leftSpaceToView(button, 0).rightSpaceToView(topView, kNavBarHeight).heightIs(20);
    
    UIView * bgView = [[UIView alloc]initWithFrame:Frame(0, kTopHeight, IPHONE_WIDTH, 65)];
    bgView.backgroundColor = self.receiveColor;
    [self.view addSubview:bgView];
    
    NSString * fourNum = [self.cardInfoModel.bankNum substringFromIndex:self.cardInfoModel.bankNum.length-4 ];
    UILabel * bankNameLab = [UILabel labelWithTitle:[NSString stringWithFormat:@"%@(尾号%@)",self.cardInfoModel.bankName,fourNum] color:[UIColor whiteColor] fontSize:15];
    [bgView addSubview:bankNameLab];
    bankNameLab.sd_layout.leftSpaceToView(bgView, 50).topSpaceToView(bgView, 10).heightIs(17);
    [bankNameLab setSingleLineAutoResizeWithMaxWidth:300];
    NSMutableDictionary * dic = [JNCardSDKCalculaterBillPayDay getBillDateAndPayDate:self.cardInfoModel.billDate andPayDay:self.cardInfoModel.dueDate];
    NSString * billStr = dic[@"finalBillDay"];
    NSString * payStr = dic[@"finalPayDay"];
    [_paraDic setObject:billStr forKey:@"BillDate"];
    [_paraDic setObject:payStr forKey:@"DueDate"];
    billStr = [billStr substringWithRange:NSMakeRange(5, 5)];
    payStr = [payStr substringWithRange:NSMakeRange(5, 5)];
    UILabel * descLab = [UILabel labelWithTitle:[NSString stringWithFormat:@"账单日%@    |    还款日%@",billStr,payStr] color:[UIColor whiteColor] fontSize:13];
    [bgView addSubview:descLab];
    descLab.sd_layout.leftEqualToView(bankNameLab).topSpaceToView(bankNameLab, 5).heightIs(15);
    [descLab setSingleLineAutoResizeWithMaxWidth:300];
    UIView * bian = [UIView new];
    bian.backgroundColor = [UIColor whiteColor];
    bian.sd_cornerRadiusFromHeightRatio = @(0.5);
    [bgView addSubview:bian];
    bian.sd_layout.leftSpaceToView(bgView, 9).centerYEqualToView(bankNameLab).offset(10).heightIs(32).widthEqualToHeight();
    
    UIImageView * bankView = [UIImageView new];
    [bankView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",JNCardSDKImageDomain,self.cardInfoModel.bankImg]]];
    bankView.backgroundColor = [UIColor whiteColor];
    bankView.sd_cornerRadiusFromHeightRatio = @(0.5);
    [bgView addSubview:bankView];
    bankView.sd_layout.leftSpaceToView(bgView, 10).centerYEqualToView(bankNameLab).offset(10).heightIs(30).widthEqualToHeight();
}
@end
